﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using umbraco.interfaces;

namespace TomMaton.Umbraco.AmazonS3
{
    public class amazonS3DataEditor : System.Web.UI.UpdatePanel, umbraco.interfaces.IDataEditor
    {
        private umbraco.interfaces.IData _data;
        private string CharLimit;
        private Literal amazonS3Files;
        private TextBox selectedFileURL;

        public amazonS3DataEditor(umbraco.interfaces.IData Data, string Configuration)
        {
            _data = Data;

            if (Configuration.Length > 0)
            {
                CharLimit = Configuration;
            }
            else
            {
                CharLimit = "100";
            }
        }

        public virtual bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public bool ShowLabel
        {
            get { return true; }
        }

        public Control Editor { get { return this; } }

        public void Save()
        {
            this._data.Value = selectedFileURL.Text;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            selectedFileURL = new TextBox();
            selectedFileURL.Text = _data.Value.ToString();
            selectedFileURL.Columns = 50;
            selectedFileURL.CssClass = "umbEditorTextField";
            selectedFileURL.ID = "selectedAmazonS3FilePath";

            amazonS3Files = new Literal();
            try
            {
                amazonS3Files.Text = String.Format("<div style=\"height:300px;overflow-y:scroll;\">{0}</div>", amazonS3Functionality.generateBucketList());
            }
            catch (Exception error)
            {
                HttpContext.Current.Response.Write(error.Message);
            }
            //amazonS3Files.Text = String.Format("Access Key:{0}<br />Secret Key:{1}", amazonS3Functionality.getKey("AccessKeyId", amazonS3Functionality.pluginConfigPath), amazonS3Functionality.getKey("SecretAccesKeyId", amazonS3Functionality.pluginConfigPath));


            base.ContentTemplateContainer.Controls.Add(selectedFileURL);
            base.ContentTemplateContainer.Controls.Add(new LiteralControl("<br />"));
            base.ContentTemplateContainer.Controls.Add(amazonS3Files);

            string functionSelectedFile = "function selectFile(selectedFilePath)";
            functionSelectedFile += "{";
            functionSelectedFile += "document.getElementById(\"ctl00_body_selectedAmazonS3FilePath\").value = selectedFilePath;";
            functionSelectedFile += "}";


            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "selectFile", functionSelectedFile, true);

        }
    }
}
